from flask import Flask, render_template, request
import pymysql

app = Flask(__name__)


@app.route("/add/user", methods=['GET', 'POST'])
def add_user():
    if request.method == "GET":
        return render_template("add_user.html")
    else:
        user = request.form.get("user")
        password = request.form.get("pwd")
        mobile = request.form.get("mobile")

        # 1. 链接Mysql
        conn = pymysql.connect(
            host="127.0.0.1",
            port=3306,
            user='root',
            password='root',
            charset='utf8',
            db='test'
        )
        cursor = conn.cursor()
        # 2. 执行SQL
        sql = "insert into user(user, password, mobile) value(%s, %s, %s)"
        cursor.execute(sql,[user, password, mobile])
        conn.commit()

        # 3. 关闭连接
        cursor.close()
        conn.close()

        return "添加成功"


@app.route("/show/user")
def show_user():
    # 1. 链接Mysql
    conn = pymysql.connect(
        host="127.0.0.1",
        port=3306,
        user='root',
        password='root',
        charset='utf8',
        db='test'
    )
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    # 2. 执行SQL
    sql = "select * from user"
    cursor.execute(sql)
    data_list = cursor.fetchall()

    # 3. 关闭连接
    cursor.close()
    conn.close()

    print(data_list)


    return render_template("show_user.html", data_list=data_list)








if __name__ == '__main__':
    app.run()

